﻿// -----------------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
//
// Licensed under the Microsoft Public License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//  
// http://opensource.org/licenses/ms-pl
//  
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// -----------------------------------------------------------------------

using Microsoft.VisualStudio.SharePoint;
using System;
using System.IO;
using System.Linq;
using System.Text;

namespace Microsoft.Samples.VisualStudio.SharePoint
{
    public static class Utilities
    {
        public static void UpdateAssemblyReferences(string file)
        {
            // UNDONE - need to do something, but not this. We need to use XML namespaces for activities, not clr namespaces.
            var contents = new StringBuilder(File.ReadAllText(file));

            contents.Replace("clr-namespace:Microsoft.SharePoint.WorkflowServices.Activities.Design;assembly=Microsoft.SharePoint.WorkflowServices.Activities.Design",
                "clr-namespace:Microsoft.SharePoint.DesignTime.Activities.Design;assembly=Microsoft.SharePoint.DesignTime.Activities.Design");
            contents.Replace("assembly=Microsoft.SharePoint.WorkflowServices.Activities", "assembly=Microsoft.SharePoint.DesignTime.Activities");
            contents.Replace("clr-namespace:Microsoft.SharePoint.WorkflowServices.Activities.Design", "clr-namespace:Microsoft.SharePoint.DesignTime.Activities");
            contents.Replace("<AssemblyReference>Microsoft.SharePoint.WorkflowServices.Activities</AssemblyReference>", "<AssemblyReference>Microsoft.SharePoint.DesignTime.Activities</AssemblyReference>");
            contents.Replace("<AssemblyReference>Microsoft.SharePoint.WorkflowServices.Activities.Design</AssemblyReference>", "<AssemblyReference>Microsoft.SharePoint.DesignTime.Activities.Design</AssemblyReference>");

            File.WriteAllText(file, contents.ToString());
        }

        public static ISharePointProjectItem CreateNewSpi(ISharePointProject project, string oldSpiName, string newSpiType)
        {
            // the format of the name will be something like this:
            // oldSpiName_App{1..n}
            int suffix = 1;
            ISharePointProjectItem newSpi = null;

            do
            {
                string newSpiName;
                do
                {
                    newSpiName = string.Format("{0}_App{1}", oldSpiName, suffix++);
                }
                while (project.ProjectItems.Where(spi => StringComparer.OrdinalIgnoreCase.Equals(spi.Name, newSpiName)).Any());

                try
                {
                    newSpi = project.ProjectItems.Add(newSpiName, newSpiType);
                    project.Synchronize();
                }
                catch
                {
                    newSpi = null;
                }
            } while (newSpi == null);

            return newSpi;
        }

        public static void CopyFiles(ISharePointProjectItem toConvertProjectItem, ISharePointProjectService projectService, ISharePointProjectItem newProjectItem, VSLangProj.prjBuildAction buildActon)
        {
            // Copy all the files in the new SPI, except for the elements.xml;
            foreach (var oldFile in toConvertProjectItem.Files)
            {
                if (oldFile.DeploymentType != DeploymentType.ElementManifest)
                {
                    var newFile = newProjectItem.Files.AddFromFileCopy(oldFile.FullPath);
                    newFile.DeploymentType = DeploymentType.AppPackage;

                    var attributes = File.GetAttributes(newFile.FullPath);
                    if (attributes.HasFlag(FileAttributes.ReadOnly))
                    {
                        attributes = attributes & ~FileAttributes.ReadOnly;
                        File.SetAttributes(newFile.FullPath, attributes);
                    }

                    if (StringComparer.OrdinalIgnoreCase.Equals(Path.GetExtension(oldFile.FullPath), ".xaml"))
                    {
                        newProjectItem.DefaultFile = oldFile;
                        projectService.Convert<ISharePointProjectItemFile, EnvDTE.ProjectItem>(newFile).SetBuildAction(buildActon);
                        newProjectItem.DefaultFile = newFile;
                        Utilities.UpdateAssemblyReferences(newFile.FullPath);
                    }
                }
            }
        }

        public static void UpdateProjectItemReferences(ISharePointProjectItem item, string errorMessage = "")
        {
            var projectService = item.Project.ProjectService;

            var xamlFile = item.Files
                .Where((file) => StringComparer.OrdinalIgnoreCase.Equals(Path.GetExtension(file.FullPath), ".xaml"))
                .FirstOrDefault();

            if (xamlFile == null)
            {
                projectService.Logger.WriteLine(errorMessage, LogCategory.Error);
                return;
            }

            Utilities.UpdateAssemblyReferences(xamlFile.FullPath);
        }
    }
}
